package com.smarttiger.zero.admin.service;

import com.smarttiger.zero.admin.dao.DictionaryDao;
import com.smarttiger.zero.admin.dto.DictionaryDto;
import com.smarttiger.zero.admin.entity.DictionaryModel;
import com.smarttiger.zero.admin.util.Constant;
import com.smarttiger.zero.admin.util.Message;
import com.smarttiger.zero.admin.util.ParamNames;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictionaryService extends BaseService<DictionaryModel>{
    @Autowired
    DictionaryDao dictionaryDao;

    @PostConstruct
    public void initMethod(){
        super.setDao(dictionaryDao);
    }

    @ParamNames("name,code,page")
    public Message getDictionarys(String name, String code,String page){
        Message message = new Message();
        Pageable pageable = PageRequest.of(Integer.valueOf(page).intValue(), Constant.PAGESIZE, Sort.by(Sort.Direction.DESC,"createDate"));
        Page<DictionaryModel> all = dictionaryDao.findAll(new Specification<DictionaryModel>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<DictionaryModel> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(code)) {
                    predicates.add(criteriaBuilder.equal(root.get("code"), code));
                }
                if (!StringUtils.isEmpty(name)) {
                    predicates.add(criteriaBuilder.like(root.get("label"), name + "%"));
                }
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createDate")));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, pageable);
        long totalElements = all.getTotalElements();
        message.setData(DictionaryDto.tranlateList(all.getContent()));
        message.setTotal((int)totalElements);
        return message;
    }

    @ParamNames("id")
    public DictionaryModel getDictionaryById(String id){
        DictionaryModel byId = dictionaryDao.findById(id).get();
        byId.getDictionaryModels();
        return byId;
    }

    @ParamNames("code")
    public DictionaryModel getDicByCode(String code){
        return dictionaryDao.getAllByCode(code);
    }
}
